#include "stdafx.h"
#include "clock.h"
#include "ui_clock.h"
#include "debug.h"
#include "connection.h"

const double PI = 3.141592;

Clock::Clock(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Clock)
{
    ui->setupUi(this);

    setWindowFlags(Qt::CustomizeWindowHint);
    setWindowFlags(Qt::WindowCloseButtonHint | Qt:: WindowMinimizeButtonHint);

	QString title("桌面闹钟 ");
	QString startTime = getStartTime();
	if (startTime.isEmpty() || startTime.isNull())
	{
		setStartTime();
		startTime = getStartTime();
	}
	title.append(startTime);
	setWindowTitle(title);

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
    timer->start(1000);

    alarmFont.setPointSize(15);
    alarmFont.setFamily("迷你简丫丫");

    cTimeLabe = new QLabel(this);
    cTimeLabe->move(20, 280);
    cTimeLabe->setFixedSize(300, 50);
    cTimeLabe->setFont(alarmFont);

    addAlarmBtn = new QPushButton("添加闹钟", this);
    addAlarmBtn->setFixedSize(100, 50);
    addAlarmBtn->setFont(alarmFont);
    addAlarmBtn->move(320, 270);
    connect( addAlarmBtn, SIGNAL(clicked()), this, SLOT(setAlarmClock()) );
    closeAlarmBtn = new QPushButton("关闭闹钟", this);
    closeAlarmBtn->setFixedSize(100, 50);
    closeAlarmBtn->setFont(alarmFont);
    closeAlarmBtn->move(440, 270);
    connect( closeAlarmBtn, SIGNAL(clicked()), this, SLOT(stopPlayMusic()) );

    player = new QMediaPlayer(this);

    model = new QSqlTableModel(this);
    model->setTable("clock");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();

    bgPixmap = QPixmap(":/images/background.png").scaled(size());
    delBtnPixmap = QPixmap(":/images/deleteBtn.png");

    updateAlarmClock();
}

Clock::~Clock()
{
    delete ui;
}


QPointF Clock::rotateAngle(int angle, int len)
{
    int x, y;

    x = 150+len*sin(angle*PI/180);
    y = 150-len*cos(angle*PI/180);

    return QPointF(x, y);
}

void Clock::paintEvent(QPaintEvent *)
{
    QTime time = QTime::currentTime();
    int timeH = time.hour();
    int timeM = time.minute();
    int timeS = time.second();

    QDateTime dateTime = QDateTime::currentDateTime();
    cTimeLabe->setText(dateTime.toString("yyyy-MM-dd hh:mm:ss ddd"));   

    QPainter painter(this);
    QPen pen;

    painter.drawPixmap(this->rect(), bgPixmap);
    pen.setWidth(1);
    pen.setColor("#333");
    painter.setPen(pen);
    for(int i=0; i<60; i++)
    {
        painter.drawLine(rotateAngle(6*i, 100), rotateAngle(6*i, 95));
    }
    pen.setWidth(5);
    painter.setPen(pen);
    painter.drawEllipse(QPoint(150, 150), 100, 100);
    pen.setWidth(3);
    painter.setPen(pen);
    for(int i=0; i<12; i++)
    {
        painter.drawLine(rotateAngle(30*i, 100), rotateAngle(30*i, 90));
    }

    pen.setWidth(2);
    pen.setColor(Qt::red);
    painter.setPen(pen);
    painter.drawLine(QPointF(150, 150), rotateAngle(6*timeS, 80));
    pen.setWidth(6);
    pen.setColor(Qt::blue);
    painter.setPen(pen);
    painter.drawLine(QPointF(150, 150), rotateAngle(6*timeM, 60));
    pen.setWidth(8);
    pen.setColor(Qt::green);
    painter.setPen(pen);
    painter.drawLine(QPointF(150, 150), rotateAngle(0.5*(timeH*60+timeM), 40));
}

void Clock::closeEvent(QCloseEvent *event)
{
	hide();
	event->ignore();
}

void Clock::timerUpdate()
{
    QTime time = QTime::currentTime();
    int timeH = time.hour();
    int timeM = time.minute();
    int timeS = time.second();

	bool raise = false;
    int rowNum = model->rowCount();
    for(int i=0; i<rowNum; i++)
    {
        if(timeH == model->index(i, 0).data().toInt()
                && timeM == model->index(i, 1).data().toInt()
                && timeS == 0)
        {
            player->setSource(QUrl::fromLocalFile(model->index(i, 2).data().toString()));
            player->play();
			raise = true;
        }
    }

	if (raise)
	{
		showNormal();
	}

    update();
}

void Clock::setAlarmClock()
{
    dialog = new QDialog(this);
    hourBox = new QSpinBox(dialog);
    minuteBox = new QSpinBox(dialog);
    pauseTime = new QComboBox(dialog);
    QLabel *label1 = new QLabel(dialog);
    QLabel *label2 = new QLabel(dialog);
    QLabel *label3 = new QLabel(dialog);
    QLabel *label4 = new QLabel(dialog);
    QPushButton *selectMusicBtn = new QPushButton("...",dialog);
	if (!musicPath.isEmpty())
	{
		selectMusicBtn->setText(QFileInfo(musicPath).fileName());
	}

	auto label5 = new QLabel(dialog);
	auto lineText = new QLineEdit(dialog);

	messageText = "";
	lineText->setText(messageText);
	connect(lineText, SIGNAL(textChanged(const QString &)), this, SLOT(textChanged(const QString & )));
	connect(lineText, SIGNAL(textEdited(const QString &)), this, SLOT(textChanged(const QString &)));

    label1->setText("闹铃时间:");
    label1->setFont(alarmFont);
    label1->move(20, 30);
    label2->setText("暂停时间:");
    label2->setFont(alarmFont);
    label2->move(20, 80);
    label3->setText("分钟");
    label3->setFont(alarmFont);
    label3->move(170, 80);
    label4->setText("选择闹铃:");
    label4->setFont(alarmFont);
    label4->move(20, 130);
	label5->setText("显示信息");
	label5->setFont(alarmFont);
	label5->move(20, 180);

	int offset = 50;
	lineText->move(120, 180);
	lineText->setFixedSize(120, 25);

    pauseTime->move(120, 80);
    pauseTime->addItem("5");
    pauseTime->addItem("10");
    pauseTime->addItem("15");
    pauseTime->addItem("20");
    pauseTime->addItem("25");
    pauseTime->addItem("30");
    pauseTime->setFont(alarmFont);

    hourBox->setPrefix("H: ");
    hourBox->setRange(0, 23);
    hourBox->setFixedSize(80, 30);
    hourBox->move(QPoint(120, 30));
    hourBox->setFont(alarmFont);
    minuteBox->setPrefix("M: ");
    minuteBox->setRange(0, 59);
    minuteBox->setFixedSize(80, 30);
    minuteBox->move(QPoint(200, 30));
    minuteBox->setFont(alarmFont);

    selectMusicBtn->move(120, 130);
    selectMusicBtn->setFixedSize(120, 30);
    connect( selectMusicBtn, SIGNAL(clicked()), this, SLOT(selectMusic()));

    QPushButton *sureBtn = new QPushButton("确定", dialog);
    QPushButton *cancelBtn = new QPushButton("取消", dialog);

    sureBtn->move(50, 180 + offset);
    sureBtn->resize(80, 30);
    sureBtn->setFont(alarmFont);
    cancelBtn->move(170, 180 + offset);
    cancelBtn->resize(80, 30);
    cancelBtn->setFont(alarmFont);

    connect( sureBtn, SIGNAL(clicked()), this, SLOT(sureAlarmClock()) );
    connect( cancelBtn, SIGNAL(clicked()), this, SLOT(cancelAlarmClock()) );

    dialog->setWindowTitle("添加闹钟");
    dialog->setFixedSize(300, 240 + offset);
    dialog->exec();
}

void Clock::updateAlarmClock()
{
    int rowNum = model->rowCount();

    for(int alarmNum=0; alarmNum<rowNum; alarmNum++)
    {
		QString showText = model->index(alarmNum, 3).data().toString();
		if (showText.isEmpty() || showText.isNull())
		{
			showText = QFileInfo(model->index(alarmNum, 2).data().toString()).fileName();
		}

        alarmLabel[alarmNum] = new QLabel(this);
        alarmLabel[alarmNum]->move(300, 30+40*alarmNum);
        alarmLabel[alarmNum]->setFixedSize(240, 30);
        alarmLabel[alarmNum]->setFont(alarmFont);
        alarmLabel[alarmNum]->setText(model->index(alarmNum, 0).data().toString()
                             + " : "
                             + model->index(alarmNum, 1).data().toString()
                             + "   "
							 + showText);
        alarmLabel[alarmNum]->setVisible(true);

        deleteAlarmBtn[alarmNum] = new QPushButton(this);
        deleteAlarmBtn[alarmNum]->move(260, 30+40*alarmNum);
        deleteAlarmBtn[alarmNum]->setFixedSize(30, 30);
        deleteAlarmBtn[alarmNum]->setIcon(delBtnPixmap);
        deleteAlarmBtn[alarmNum]->setFlat(true);
        deleteAlarmBtn[alarmNum]->setVisible(true);
        connect( deleteAlarmBtn[alarmNum], SIGNAL(clicked()), this, SLOT(deleteAlarm()) );
    }
}

void Clock::sureAlarmClock()
{
    alarmHour = hourBox->value();
    alarmMinute = minuteBox->value();

    cPauseTime = pauseTime->currentText().toInt();

    int rowNum = model->rowCount();
    if(rowNum < 5)
    {
        model->insertRow(rowNum);
        model->setData(model->index(rowNum, 0), alarmHour);
        model->setData(model->index(rowNum, 1), alarmMinute);
        model->setData(model->index(rowNum, 2), musicPath);
		model->setData(model->index(rowNum, 3), messageText);
        model->submitAll();
        model->setTable("clock");
        model->select();

        for(int i=0; i<rowNum; i++)
        {
            delete alarmLabel[i];
            delete deleteAlarmBtn[i];
        }

        qDebug() << model->index(rowNum, 0).data().toString()
                    << model->index(rowNum, 1).data().toString()
                       << QFileInfo( model->index(rowNum, 2).data().toString() ).fileName();

        updateAlarmClock();
    }
    else
    {
        QMessageBox::warning(this, "警告", "闹钟数量已达上限!", QMessageBox::Yes);
    }

    dialog->close();
}

void Clock::cancelAlarmClock()
{
    dialog->close();
}

void Clock::stopPlayMusic()
{
    player->stop();
}

void Clock::selectMusic()
{
	musicPath = QFileDialog::getOpenFileName(this, "选择铃声",
		"H:\\Desktop\\WaveTest\\", "*.mp3");

	auto seletBtn = qobject_cast<QPushButton*>(QObject::sender());
	if (seletBtn)
	{
		if (musicPath.isEmpty() ||
			musicPath.isNull()
			)
		{
			seletBtn->setText("...");
		}
		else
		{
			seletBtn->setText(QFileInfo(musicPath).fileName());
		}
	}
}

void Clock::rePlayMusic()
{
    player->play();
}

void Clock::textChanged(const QString & text)
{
	messageText = text;
}

void Clock::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
	switch (reason) {
	case QSystemTrayIcon::Trigger:
	case QSystemTrayIcon::DoubleClick:
		if (!isVisible())
		{
			showNormal();
		}
		break;
	default:
		;
	}
}

void Clock::deleteAlarm()
{
    int rowNum = model->rowCount();

    qDebug() << rowNum;

    QPushButton *btn = qobject_cast<QPushButton*>(QObject::sender());
    if( btn == deleteAlarmBtn[0] )
    {
        model->removeRows(0, 1);
        qDebug() << "delete 0";
    }
    else if( btn == deleteAlarmBtn[1] )
    {
        model->removeRows(1, 1);

        qDebug() << "delete 1";
    }
    else if( btn == deleteAlarmBtn[2] )
    {
        model->removeRows(2, 1);
        qDebug() << "delete 2";
    }
    else if( btn == deleteAlarmBtn[3] )
    {
        model->removeRows(3, 1);
    }
    else if( btn == deleteAlarmBtn[4])
    {
        model->removeRows(4, 1);
    }

    int ok = QMessageBox::warning(this, "删除当前闹钟!",
                                   "您确定删除当前闹钟吗?",
                                  QMessageBox::Yes, QMessageBox::No);
    if(ok == QMessageBox::No)
    {
        model->revertAll();

        qDebug() << rowNum;
    }
    else
    {
        for(int i=0; i<rowNum; i++)
        {
            delete alarmLabel[i];
            delete deleteAlarmBtn[i];
        }

        model->submitAll();

        updateAlarmClock();

        rowNum = model->rowCount();

        qDebug() << rowNum;
    }
}
